// miniprogram/pages/me/me.js
var app = getApp()
Page({
  data: {
    active: "me",
    showName: false,
    label: "姓名",
    key: "name",
    userInfo: {
      name: "hahah",
      stuNo: "121222",
      school: "计算机学院",
      tel: "12344412",
      email: "1212@gmail.com"
    },
    newValue: ""
  },
  onLoad: function(opts) {
    console.log("----------------------", app.globalData)
    this.setData({
      userInfo: app.globalData.userInfo
    })
    console.log(this.data.userInfo)
  },

  onChange(event) {
    console.log(event.detail)
    this.setData({
      active: event.detail,
    });

    let that = this
    wx.navigateTo({
      url: "/pages/" + that.data.active + "/" + that.data.active
    })
  },
  onChangeName(e) {
    console.log(e)
    this.setData({
      showName: true,
      label: "姓名",
      key: "name",
      value: this.data.userInfo.name
    })

  },
  onChangeStuNo(e) {
    this.setData({
      showName: true,
      label: "学号",
      key: "stuNo",

      newValue: this.data.userInfo.stuNo
    })
  },
  onChangeSchool(e) {
    this.setData({
      showName: true,
      label: "院系",
      key: "school",

      newValue: this.data.userInfo.school
    })
  },
  onChangeTel(e) {
    this.setData({
      showName: true,
      label: "手机",
      key: "tel",
      newValue: this.data.userInfo.tel
    })
  },
  onChangeEmail(e) {
    this.setData({
      showName: true,
      label: "邮箱",
      key: "email",

      newValue: this.data.userInfo.email
    })
  },
  onClose() {
    console.log("onClose")
    this.setData({
      showName: false
    });
  },
  onUpdate(e) {
    let that = this
    let key = e.currentTarget.dataset.key
    console.log(key, this.data)
    this.data.userInfo[key] = this.data.newValue
    this.setData({
      userInfo: this.data.userInfo,
      newValue: "",
      showName: false
    })
    console.log(e)



    // 更新数据库
    wx.cloud.callFunction({
      name: "updateUser",
      data: {
        userInfo: {
          name: that.data.userInfo.name,
          stuNo: that.data.userInfo.stuNo,
          school: that.data.userInfo.tel,
          tel: that.data.userInfo.school,
          email: that.data.userInfo.email,
          _id: that.data.userInfo._id
        }
      },
      success: res => {
        console.log("res", res)
      },

      fail: res => {
        console.log("res", res)
      }
    })
  },
  onInputChange: function(e) {
    this.setData({
      newValue: e.detail
    })
  }
})